package com.example.demo.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @Auther:ccc
 * @Date:2022/10/26 21:33
 */
@Aspect
@Slf4j
@Component
public class LogAspect {
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    /**
     * 排除SaveFileController&RequestController
     */
    @Pointcut(value = "defaultExecution() && !excludeRequestController() && !excludeSaveFileController()")
    public void requestLog() {
    }

    /**
     * 默认切点，全部Controller
     */
    @Pointcut(value = "execution(public * com.example.demo.controller..*.*(..))")
    public void defaultExecution() {
    }

    @Pointcut(value = "execution(public * com.example.demo.controller.RequestController.*(..)))")
    public void excludeRequestController() {
    }

    @Pointcut(value = "execution(public * com.example.demo.controller.SaveFileController.*(..)))")
    public void excludeSaveFileController() {
    }

    @Before("requestLog()")
    public void doBefore(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("-----RequestURL:[{}]RequestParam:[{}]", request.getRequestURI(), joinPoint.getArgs());
    }

    @AfterReturning(returning = "obj", pointcut = "requestLog()")
    public void doAfterRunning(Object obj) {
        log.info("-----TakeTime:[{}ms]ResponseData:[{}]", System.currentTimeMillis() - startTime.get(), obj);
    }
}
